package service.impl;

import common.impl.exception.ServiceException;

import model.MReading;
import net.sf.json.JSONObject;
import service.interf.IReading;
import dao.interf.IReadingDao;
import dao.pojo.Reading;



public class ReadingImpl implements IReading{
	private IReadingDao readingDao;
	
	public void setreadingDao(IReadingDao readingDao) {
		this.readingDao = readingDao;
	}
	
	@Override
	public String add(MReading model) {
		Reading reading = new Reading();
		
	

		return readingDao.add(reading);
	}
	
	@Override
	public String getById(MReading model) {
	Reading reading = readingDao.getById(model.getReadId());
	if(null == reading) {
		throw new ServiceException("ERR-0121");
	}
		return createReadingObj(reading).toString();
	}

	@Override
	public String deleteById(Integer id) {
		readingDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MReading model) {
		Reading reading = readingDao.getById(model.getReadId());
		if (null == reading) {
			throw new ServiceException("ERR-0121");
		}
		

		readingDao.edit(reading);
		return "1";
	}
	
	public JSONObject createReadingObj(Reading reading) {
		JSONObject obj = new JSONObject();
		
		obj.put("readId", reading.getReadId());
		obj.put("readDirection", reading.getReadDirection());
		if(null != reading.getPassageByPassageIid())
			obj.put("passageIId", reading.getPassageByPassageIid().getPassageId());
		if(null != reading.getPassageByPassageIiid())
			obj.put("passageIIId", reading.getPassageByPassageIiid().getPassageId());
		obj.put("readI", reading.getReadI());
		obj.put("readII", reading.getReadIi());
		obj.put("readIKeys", reading.getReadIkeys());
		obj.put("readIIKeys", reading.getReadIikeys());
		
		return obj;
	}


}
